--- 模块功能：串口功能测试(TASK版)
-- @author openLuat
-- @module uart.testUartTask
-- @license MIT
-- @copyright openLuat
-- @release 2018.10.20
require "pm"
require "ril"
require "ntp"
require "nvm"
require "gps"
require "http"
require "mqtt"
require "utils"
require "config"
require "sessor"
require "socket"
require "lbsLoc"
module(..., package.seeall)

---[[
-- 天气应用使用了 "和风天气免费 API 演示，用于商业目的请购买商用许可 API"
-- https://dev.heweather.com/
-- 天气应用图标使用了 和风天气开源 天气图标：
-- https://dev.heweather.com/docs/start/icons
-- 再次对和风天气的开源表示感谢！
--]]
net.switchFly(false)
local lcd = require "gdew027w3"
--如果是关机闹钟开机，则需要软件主动重启一次，才能启动GSM协议栈
if rtos.poweron_reason() == rtos.POWERON_ALARM then
    sys.restart("ALARM")
end
--]]
--注册闹钟模块
rtos.init_module(rtos.MOD_ALARM)
--注册闹钟消息的处理函数
rtos.on(rtos.MSG_ALARM, function()
    log.info("---------- 温湿度采集器被唤醒! ----------")
end)

--- 测试 SHT30 和 KXTJ3 传感器
sys.taskInit(function()
        -- sys.wait(5000)
        -- i2c_open(0)
        while true do
            sessor.sht30(0, 0x44)
            sys.wait(1000)
            sessor.dcst();
            -- sys.wait(1000)
            -- writeReg(0, KXTJ3_ADDR, 0x6A, 0x3c, 0x40)
            sys.wait(5000)
        -- local c = os.date("*t", os.time() + sleepTime * 60)
        -- log.warn("下次开机的时间:", os.date("%Y-%m-%d %H:%M:%S", os.time() + sleepTime * 60))
        -- rtos.set_alarm(1, c.year, c.month, c.day, c.hour, c.min, c.sec)
        -- rtos.poweroff()
        end
-- i2c.close(0)
end)
-------------------------------- 处理网络应用 --------------------------------
local host, port = "180.97.80.55", "12415"
-- 创建 uart 和 socket 对象
local u1 = uart.new(1, 115200)
local sc = socket.new(host, port, "tcp")
sc:on("open", function()
    sc:send("hello socket server!")
end)
u1:on("recv", function(msg)
    log.info("收到串口发来的数据:", msg)
    sc:send(msg)
end)
sc:on("open", function()
    sc:send("hello socket server!")
end)
sc:on("recv", function(msg)
    log.info("收到 socket server 的消息:", msg)
    u1:send(msg)
end)
sc:on("sent", function()
    log.info("sent to socket:", "发送消息已完成!")
end)
sc:on("error", function(msg)
    log.error("socket error:", msg)
end)
sc:on("close", function(code)
    log.info("socket closed,关闭码:", code)
end)
-- 启动任务进程
-- sys.taskInit(sc.start, sc, 180)
-- sys.taskInit(u1.start, u1, nil, 10)
-------------------------------- 处理天气预报应用 --------------------------------
-- 城市, 区县
local weather = {
    city = "北京",
    county = "天安门",
    text = "雨",
    windDir = "西南风",
    windScale = "3",
    temp = "31",
    humidity = "34"
}
sys.taskInit(function()
    while not socket.isReady() do sys.wait(5000) end
    sys.wait(5000)
    while true do
        while true do
            local url = "https://geoapi.heweather.net/v2/city/lookup"
            local lng, lat = lbsLoc.request()
            if lng and lng then
                local loc = string.format("%f,%f", lng, lat)
                local code, head, body = http.request("GET", url, 30000, {location = loc, key = "40630cb62d7b401c85d049e242a72a58", gzip = "n"}, nil, 1, basic, headers, cert)
                log.info("当前城市是:", body)
                if code:sub(1, 1) == "2" then
                    local t = json.decode(body)
                    if t and t.location then
                        -- log.info("--->location1.adm2,name", t.location.adm2, t.location.name)
                        -- log.info("--->location2.adm2,name", t.location[1].adm2, t.location[1].name)
                        weather.city = t.location[1].adm2 or weather.city
                        weather.county = t.location[1].name or weather.county
                    end
                end
                url = "https://devapi.heweather.net/v7/weather/now?"
                code, head, body = http.request("GET", url, 30000, {location = loc, key = "40630cb62d7b401c85d049e242a72a58", gzip = "n"}, nil, 1, basic, headers, cert)
                log.info("当前城市天气:", body)
                if code:sub(1, 1) == "2" then
                    local t = json.decode(body)
                    if t and t.now then
                        weather.text = t.now.text or weather.text
                        weather.windDir = t.now.windDir or weather.windDir
                        weather.windScale = t.now.windScale or weather.windScale
                        weather.temp = t.now.temp or weather.temp
                        weather.humidity = t.now.humidity or weather.humidity
                        sys.publish("UPGRADE_NOW")
                        break
                    end
                end
                for k, v in pairs(weather) do
                    log.info("当前城市天气信息:", k, v)
                end
            end
            sys.wait(10000)
        end
        sys.waitUntil("UPGRADE_WAIT", 3600 * 1000)
    end
end)

-------------------------------- 处理屏幕应用 --------------------------------
sys.taskInit(function()
    sys.wait(2000)
    lcd.Open()
    while true do
        sys.waitUntil("UPGRADE_NOW", 10 * 1000)
        local temp, hum = sessor.sht30(0, 0x44)
        -- 显示年月日
        local c = misc.getClock()
        local t = lcd.GetBmpData("/lua/weather-bg.bmp")
        -- 天气预报部分
        lcd.PutString(1, 66, common.utf8ToGb2312(weather.text), "gb2312_16x16", t)--天气
        lcd.PutString(1, 99, common.utf8ToGb2312(weather.city), "gb2312_16x16", t)-- 城市
        lcd.PutString(1, 117, common.utf8ToGb2312(weather.county), "gb2312_16x16", t)-- 区县
        lcd.PutString(8, 117, common.utf8ToGb2312(weather.windDir), "gb2312_16x16", t)-- 风
        lcd.PutString(14, 117, weather.windScale .. "F", "font8x16", t)-- 风
        -- 显示星期
        lcd.PutString(24, 32, tostring(misc.getWeek()), "font32x64", t)
        lcd.PutString(19, 8, string.format("%d/%02d/%02d", c.year, c.month, c.day), "font8x16", t)
        -- 显示 时间
        lcd.PutString(19, 100, string.format("%02d:%02d", c.hour, c.min), "font16x32", t)
        lcd.PutString(1, 140, tostring(temp), "font16x32", t)
        lcd.PutString(17, 140, tostring(hum), "font16x32", t)
        lcd.Display(lcd.RowToColu(t))
        -- lcd.Sleep()
    end
end)

-------------------------------- GPS 测试 --------------------------------
-- gps.open(3, 9600, 10, false, true)
sys.subscribe("GPS_MSG_REPORT", function(...)
    log.info("MSG:", unpack(arg))
    log.info("MSG-INT:", gps.isFix(), gps.getIntLocation())
    log.info("MSG-gcj02:", gps.isFix(), gps.getGcj02())
    log.info("MSG-gcbd09:", gps.isFix(), gps.getBd09())
end)

-------------------------------- 系统监视 --------------------------------
sys.timerLoopStart(function()
    local ram, rom = _G.collectgarbage("count"), rtos.get_fs_free_size()
    log.info("打印占用的内存(KB):", (ram - (ram % 1)), "KB")-- 打印占用的RAM
    log.info("打印可用的空间(KB)", (rom - (rom % 1024)) / 1024, "KB")-- 打印剩余FALSH
end, 3000)
